package com.xh.rabbit_pay.controller;

import com.xh.rabbit_pay.dao.PayDao;
import com.xh.rabbit_pay.entity.Pay;
import com.xh.rabbit_pay.util.Utils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderController {

    @Autowired
    private RabbitTemplate rabbit;

    @Autowired
    private PayDao payDao;

    @RequestMapping("/order")
    public String order(Model model) throws ExecutionException, InterruptedException {

        //封装订单信息
        Pay pay = new Pay();
        pay.setId(Utils.generatePayId());
        pay.setStatus("0");
        pay.setRemark("待支付");

        CorrelationData correlationData = new CorrelationData();
        rabbit.convertAndSend("x.order", "k.order", pay, correlationData);

        // 同步等待发送订单到MQ的结果，可以设置为异步回调
        CorrelationData.Confirm confirm = correlationData.getFuture().get();

        // 判断发送的消息是否得到broke的确认
        boolean isAcked = confirm.isAck();

        if (!isAcked) return "failorder";
        payDao.insert(pay);

        // 如果获取broker的确认，则表示订单已经到订单MQ中，
        // 此时向延迟队列中发送延迟等待消息
        rabbit.convertAndSend("x.ttl", "k.ttl", pay.getId());

        model.addAttribute("payId", pay.getId());

        return "order";
    }

    @RequestMapping("/failorder/{payId}")
    public String failOrder(@PathVariable Integer payId, Model model) {
        model.addAttribute("payId", payId);
        Pay pay = payDao.findCode(payId);
        pay.setStatus("2");
        pay.setRemark("未支付");
        payDao.upDate(pay);
        return "fail";
    }


















}
